/*
 * Generated on 24/01/18 (Christian Fischer)
 * Rackles et al. Impaired peroxisomal import triggers a peroxisomal retrograde signaling 
 *
 * Macro for automated image processing and analysis
 * 
 * Opens all files in folder (only image files should be in folder) and performs the following operations on each image:
 * 
 * - Setting pixel width and length to physical value (in this case 67 nm, code needs to be changed for 3d images!) 
 * - Background subtraction
 * - Image duplication for later image multiplication
 * - Otsu autothreshold 
 * - Invert
 * - Analyze particles (to remove unwanted noise)
 * - Divide by 255
 * - Multiply mask with original image
 * - 3D Objects counter to count all objects and measure different properties (intensity, size, etc.) 
 * - Saves results for each image as csv file (named after the original image) 
 * 
 * 
 */


out=getDirectory("Select Folder in which all images for quantification are stored");
names=getFileList(out);

setBatchMode(true); 

for (i = 0; i<names.length; i++){

	open(out + names[i]);
	rename("original");

	run("Properties...", "channels=1 slices=1 frames=1 unit=nm pixel_width=67 pixel_height=67 voxel_depth=1");
	
	run("Subtract Background...", "rolling=5");
	
	run("Duplicate...", " ");
	rename("duplicate");

	run("Auto Threshold", "method=Otsu white");

	run("Invert");

	run("Analyze Particles...", "size=4-Infinity show=Masks");
	rename("duplicate_mask");

	selectWindow("duplicate");
	run("Close"); 

	selectWindow("duplicate_mask");
	run("Divide...", "value=255.000");

	imageCalculator("Multiply create", "original","duplicate_mask");

	selectWindow("Result of original");
	run("3D Objects Counter", "threshold=1 slice=1 min.=1 max.=1339000 exclude_objects_on_edges statistics summary");

	selectWindow("Statistics for Result of original");
	saveAs("Results", out + names[i] + ".csv");
	run("Close"); 

	run("Close All");
		
}